package cs575.server.services;

import java.nio.ByteBuffer;
import java.util.Vector;

import cs575.common.FantasyMessage;
import cs575.common.OpCodes;
import cs575.common.Player;
import cs575.server.FantasyServer;

/**
 * Service that receives a request for player statistics, consults the master
 * service list, and returns a message containing the requested player data.
 */
public class GetPlayer {
	public FantasyMessage execute(FantasyMessage message) {
		ByteBuffer m = ByteBuffer.wrap(message.getMessage());

		int numPlayers = m.getInt();
		// Size of integer, number of players returned.
		int responseMsgSize = 4;
		int numPlayersReturned = 0;
		Vector<Player> toReturn = new Vector<Player>();

		for (int i = 0; i < numPlayers; i++) {
			int nSize = m.getInt();
			byte[] nBytes = new byte[nSize];
			m.get(nBytes);
			String name = new String(nBytes);

			if (FantasyServer.doesPlayerExist(name)) {
				Player p = FantasyServer.getPlayer(name);
				numPlayersReturned++;
				toReturn.add(p);
				// Magic number - 4 is the size on an integer
				responseMsgSize += p.size() + 4;
			}
		}

		ByteBuffer responseBB = ByteBuffer.allocate(responseMsgSize);
		responseBB.putInt(numPlayersReturned);

		for (Player p : toReturn) {
			responseBB.putInt(p.size());
			responseBB.put(p.toBytes());
		}

		FantasyMessage response = new FantasyMessage();
		response.setOpCode(OpCodes.REQUEST_PLAYER_RESPONSE);
		response.setMessage(responseBB.array());
		return response;

	}
}
